import { reactive, ref, onUnmounted } from 'vue'

export function useGameLogic() {
  const BOARD_SIZE = 8
  const COLORS = 6
  const INITIAL_MOVES = 30
  const GAME_TIME = 60 // 60秒游戏时间
  const TARGET_SCORE = 1000 // 目标分数
  
  const board = reactive([])
  const score = ref(0)
  const moves = ref(INITIAL_MOVES)
  const timeLeft = ref(GAME_TIME)
  const targetScore = ref(TARGET_SCORE)
  const gameOver = ref(false)
  const gameWon = ref(false)
  const gameStarted = ref(false)
  
  let gameTimer = null
  
  // 初始化游戏板
  const initBoard = () => {
    board.length = 0
    for (let i = 0; i < BOARD_SIZE * BOARD_SIZE; i++) {
      board.push({
        color: Math.floor(Math.random() * COLORS),
        selected: false,
        disappearing: false,
        falling: false,
        fallDelay: 0,
        fallDistance: 0
      })
    }
  }
  
  // 开始游戏计时器
  const startGameTimer = () => {
    if (gameTimer) return
    
    gameStarted.value = true
    gameTimer = setInterval(() => {
      timeLeft.value--
      
      if (timeLeft.value <= 0) {
        endGame(false) // 时间到，游戏失败
      }
    }, 1000)
  }
  
  // 结束游戏
  const endGame = (won = false) => {
    if (gameTimer) {
      clearInterval(gameTimer)
      gameTimer = null
    }
    
    gameOver.value = true
    gameWon.value = won
  }
  
  // 检查胜利条件
  const checkWinCondition = () => {
    if (score.value >= targetScore.value) {
      endGame(true) // 达到目标分数，游戏胜利
    }
  }
  
  // 获取行列坐标
  const getRowCol = (index) => {
    return {
      row: Math.floor(index / BOARD_SIZE),
      col: index % BOARD_SIZE
    }
  }
  
  // 获取索引
  const getIndex = (row, col) => {
    return row * BOARD_SIZE + col
  }
  
  // 获取相邻的相同颜色方块
  const getConnectedCells = (index, color, visited = new Set()) => {
    if (visited.has(index)) return []
    visited.add(index)
    
    const connected = [index]
    const { row, col } = getRowCol(index)
    
    // 检查四个方向
    const directions = [
      { dr: -1, dc: 0 }, // 上
      { dr: 1, dc: 0 },  // 下
      { dr: 0, dc: -1 }, // 左
      { dr: 0, dc: 1 }   // 右
    ]
    
    directions.forEach(({ dr, dc }) => {
      const newRow = row + dr
      const newCol = col + dc
      const newIndex = getIndex(newRow, newCol)
      
      if (newRow >= 0 && newRow < BOARD_SIZE && 
          newCol >= 0 && newCol < BOARD_SIZE &&
          board[newIndex] && board[newIndex].color === color &&
          !visited.has(newIndex)) {
        connected.push(...getConnectedCells(newIndex, color, visited))
      }
    })
    
    return connected
  }
  
  // 超级丝滑的方块下落系统
  const applyGravity = () => {
    let hasChanges = false
    let maxFallDelay = 0
    
    // 收集所有列的变化信息
    const columnChanges = []
    
    for (let col = 0; col < BOARD_SIZE; col++) {
      const survivingBlocks = []
      let removedCount = 0
      
      for (let row = BOARD_SIZE - 1; row >= 0; row--) {
        const index = getIndex(row, col)
        if (!board[index].disappearing) {
          survivingBlocks.push({
            color: board[index].color,
            originalRow: row
          })
        } else {
          removedCount++
        }
      }
      
      if (removedCount > 0) {
        hasChanges = true
        columnChanges.push({
          col,
          survivingBlocks,
          removedCount
        })
      }
    }
    
    if (!hasChanges) return
    
    // 统一处理所有列的变化
    columnChanges.forEach(({ col, survivingBlocks, removedCount }) => {
      // 生成新方块
      const newBlocks = []
      for (let i = 0; i < removedCount; i++) {
        newBlocks.push({
          color: Math.floor(Math.random() * COLORS),
          isNew: true,
          newBlockIndex: i
        })
      }
      
      // 合并新方块和原有方块
      const allBlocks = [...newBlocks, ...survivingBlocks.reverse()]
      
      // 为每个位置分配方块并计算超级丝滑的动画参数
      for (let row = 0; row < BOARD_SIZE; row++) {
        const index = getIndex(row, col)
        const blockData = allBlocks[row]
        
        let fallDelay = 0
        let fallDistance = 0
        let isNew = false
        
        if (blockData.isNew) {
          // 新方块从顶部外进入
          isNew = true
          fallDistance = BOARD_SIZE + blockData.newBlockIndex + 2 // 增加额外高度
          
          // 优化新方块延迟：基于位置和轻微随机性
          const baseDelay = blockData.newBlockIndex * 35
          const columnStagger = col * 6 // 列间错开
          const randomJitter = Math.random() * 12 // 轻微随机性
          fallDelay = baseDelay + columnStagger + randomJitter
          
        } else {
          // 原有方块下落
          const originalRow = blockData.originalRow
          fallDistance = row - originalRow
          
          if (fallDistance > 0) {
            // 超级优化的原有方块延迟算法
            const baseDelay = (fallDistance - 1) * 28 // 减少基础延迟
            const columnFlow = col * 4 // 减少列间差异
            const distanceBonus = Math.max(0, fallDistance - 2) * 8 // 远距离额外延迟
            const smoothing = Math.random() * 8 // 微妙随机性
            
            fallDelay = baseDelay + columnFlow + distanceBonus + smoothing
          }
        }
        
        // 更新方块状态
        board[index] = {
          color: blockData.color,
          selected: false,
          disappearing: false,
          falling: fallDistance > 0 || isNew,
          fallDelay: Math.round(fallDelay),
          fallDistance: Math.max(fallDistance, 1),
          isNewBlock: isNew
        }
        
        maxFallDelay = Math.max(maxFallDelay, fallDelay)
      }
    })
    
    // 启动超级流畅的分阶段下落动画
    if (hasChanges) {
      // 先将所有延迟方块设为不下落状态
      board.forEach(cell => {
        if (cell.falling && cell.fallDelay > 0) {
          cell.falling = false
        }
      })
      
      // 创建优雅的下落序列，按延迟排序
      const fallSequence = []
      board.forEach((cell, index) => {
        if (cell.fallDelay > 0) {
          fallSequence.push({ index, delay: cell.fallDelay })
        }
      })
      
      fallSequence.sort((a, b) => a.delay - b.delay)
      
      // 分批触发下落动画，间隔更小更流畅
      fallSequence.forEach(({ index, delay }) => {
        setTimeout(() => {
          if (board[index] && board[index].fallDelay > 0) {
            board[index].falling = true
          }
        }, delay)
      })
      
      // 在所有动画完成后清理状态
      const totalAnimationTime = maxFallDelay + 500 // 减少总等待时间
      setTimeout(() => {
        board.forEach(cell => {
          cell.falling = false
          cell.fallDelay = 0
          cell.fallDistance = 0
          cell.isNewBlock = false
        })
      }, totalAnimationTime)
    }
  }
  
  // 选择方块
  const selectCell = (index) => {
    if (gameOver.value || moves.value <= 0 || timeLeft.value <= 0) return
    
    // 首次点击开始计时
    if (!gameStarted.value) {
      startGameTimer()
    }
    
    const cell = board[index]
    const connectedCells = getConnectedCells(index, cell.color)
    
    if (connectedCells.length >= 2) {
      // 标记为消失动画
      connectedCells.forEach(cellIndex => {
        board[cellIndex].disappearing = true
      })
      
      // 延迟消除和计分
      setTimeout(() => {
        const pointsEarned = connectedCells.length * 10 + (connectedCells.length - 2) * 5
        score.value += pointsEarned
        moves.value--
        
        // 检查胜利条件
        checkWinCondition()
        
        // 应用重力，让方块下落填补
        applyGravity()
        
        // 检查游戏是否结束（步数用完）
        if (moves.value <= 0 && !gameOver.value) {
          endGame(false)
        }
      }, 350) // 进一步减少延迟，提高响应性
    }
  }
  
  // 提示功能
  const hint = () => {
    if (gameOver.value || moves.value <= 0 || timeLeft.value <= 0) return
    
    // 清除之前的选中状态
    board.forEach(cell => cell.selected = false)
    
    // 寻找可消除的方块组合
    for (let i = 0; i < board.length; i++) {
      if (!board[i].disappearing && !board[i].falling) {
        const connectedCells = getConnectedCells(i, board[i].color)
        if (connectedCells.length >= 2) {
          connectedCells.forEach(index => {
            board[index].selected = true
          })
          
          // 3秒后取消高亮
          setTimeout(() => {
            board.forEach(cell => cell.selected = false)
          }, 3000)
          return
        }
      }
    }
  }
  
  // 重置游戏
  const resetGame = () => {
    if (gameTimer) {
      clearInterval(gameTimer)
      gameTimer = null
    }
    
    score.value = 0
    moves.value = INITIAL_MOVES
    timeLeft.value = GAME_TIME
    gameOver.value = false
    gameWon.value = false
    gameStarted.value = false
    initBoard()
  }
  
  // 清理定时器
  onUnmounted(() => {
    if (gameTimer) {
      clearInterval(gameTimer)
    }
  })
  
  return {
    board,
    score,
    moves,
    timeLeft,
    targetScore,
    gameOver,
    gameWon,
    gameStarted,
    initBoard,
    selectCell,
    resetGame,
    hint
  }
} 